package com.visizen.wisdomclass.server.action.User;

import com.alibaba.fastjson.JSONObject;
import com.visizen.wisdomclass.server.action.response.ErrorCode;
import com.visizen.wisdomclass.server.action.response.ErrorCodeManager;
import com.visizen.wisdomclass.server.action.response.Result;
import com.visizen.wisdomclass.server.model.WcEquipment;
import com.visizen.wisdomclass.server.model.WcUser;
import com.visizen.wisdomclass.server.service.EquipmentService;
import com.visizen.wisdomclass.server.service.LoginLogService;
import com.visizen.wisdomclass.server.service.UserService;
import com.visizen.wisdomclass.server.token.WCToken;
import com.visizen.wisdomclass.server.token.WCTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 【用户】通过username进行登录<br/>
 * Created on 14-5-13
 *
 * @author rankun203@gmail.com
 */
@Controller
@RequestMapping("/User")
public class UserLoginAction {

    /**
     * 用户登录 [login,POST] 所有用户，无论角色都通过这个API进行登录，基于WC_USER表<br/>
     *
     * @param username  用户名，最大长度32位，最小长度8位
     * @param passmd5   密码的MD5值，长度为32位，直接根据密码生成MD5
     * @param equipUUID 登录设备的UUID
     * @param token     Token令牌，是服务器派发给用户的操作令牌，为32位的MD5值
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result loginByUsername(@RequestParam(required = true) String username,
                                  @RequestParam(required = true) String passmd5,
                                  @RequestParam(required = true) String equipUUID,
                                  @RequestParam(required = false) String token,
                                  HttpServletRequest request) {
        //开始构造返回对象
        Result result = new Result();
        JSONObject jo = new JSONObject();

        /**
         * 判断用户名和密码是否匹配
         */
        boolean isCorrectUser = userService.checkCorrectUsernameByPassword(username, passmd5);

        if (isCorrectUser) {
            /**
             * 用户名和密码匹配
             */
            WcUser user = userService.getUserByUsername(username);
            WCToken wcToken = tokenManager.generateToken(user);
            jo.put("token", wcToken.getTokenId());

            /**
             * 记录用户的登录日志
             */
            WcEquipment equipment = equipmentService.selectByUUID(equipUUID);
            loginLogService.newLoginByUsernameLog(user.getUser_id(), equipment.getEquip_id());

            //创建一个成功的返回结果
            result.setSuccessResult(request, "", jo);
        } else {
            /**
             * 用户名和密码不匹配，判断用户名是否存在
             */
            boolean isUsernameExist = userService.checkUserExistByUsername(username);
            jo.put("exception", "");
            if (isUsernameExist) {
                /**
                 * 用户名存在，则表明是密码错误
                 */
                ErrorCodeManager codeManager = ErrorCodeManager.getLocalMsg(ErrorCode.C1015_wrongPassmd5);
                /**
                 * 返回登录失败的错误信息
                 */
                result.setFailedResult(request, codeManager.getCode(), codeManager.getMsg(), jo);

            } else {
                /**
                 * 用户名不存在
                 */
                ErrorCodeManager codeManager = ErrorCodeManager.getLocalMsg(ErrorCode.C1010_userNotExists);
                result.setFailedResult(request, codeManager.getCode(), codeManager.getMsg(), jo);
            }
        }
        return result;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setTokenManager(WCTokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Autowired
    public void setEquipmentService(EquipmentService equipmentService) {
        this.equipmentService = equipmentService;
    }

    @Autowired
    public void setLoginLogService(LoginLogService loginLogService) {
        this.loginLogService = loginLogService;
    }

    private UserService userService;
    private WCTokenManager tokenManager;
    private LoginLogService loginLogService;
    private EquipmentService equipmentService;

}
